<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="楼层" prop="floor">
        <el-input
            v-model="queryParams.floor"
            placeholder="请输入楼层"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间号" prop="roomNumber">
        <el-input
            v-model="queryParams.roomNumber"
            placeholder="请输入房间号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间类型" prop="roomTypeId">
        <el-select
            style="width: 110px"
            v-model="queryParams.roomTypeId"
            placeholder="请选择"
            clearable
            @change="handleQuery"
        >
          <el-option
              v-for="type in roomTypeList"
              :key="type.value"
              :label="type.label"
              :value="type.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" style="width: 110px" placeholder="请选择" clearable>
          <el-option
              v-for="dict in sys_room_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="入住时间" prop="checkinTime">-->
<!--        <el-date-picker clearable-->
<!--                        v-model="queryParams.checkinTime"-->
<!--                        type="date"-->
<!--                        value-format="YYYY-MM-DD"-->
<!--                        placeholder="请选择入住时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="退房时间" prop="checkoutTime">-->
<!--        <el-date-picker clearable-->
<!--                        v-model="queryParams.checkoutTime"-->
<!--                        type="date"-->
<!--                        value-format="YYYY-MM-DD"-->
<!--                        placeholder="请选择退房时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:hotel_room:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:hotel_room:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:hotel_room:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:hotel_room:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="酒店名" align="center" prop="hotelInfo.hotelName" />
      <el-table-column label="房间类型" align="center" prop="roomTypeId">
        <template #default="scope">
          <span>{{ roomTypeList.find(type => type.value === scope.row.roomTypeId)?.label || scope.row.roomTypeId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="楼层" align="center" prop="floor" />
      <el-table-column label="房间号" align="center" prop="roomNumber" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_room_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="入住时间" align="center" prop="checkinTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.checkinTime, '{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退房时间" align="center" prop="checkoutTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.checkoutTime, '{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:hotel_room:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:hotel_room:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改房间信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roomRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="酒店名" prop="hotelId">
          <el-input v-model="form.hotelId" disabled />
        </el-form-item>
        <el-form-item label="房间类型" prop="roomTypeId">
          <el-select
              style="width: 100%"
              v-model="form.roomTypeId"
              placeholder="请选择"
              clearable
          >
            <el-option
                v-for="type in roomTypeList"
                :key="type.value"
                :label="type.label"
                :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-input v-model="form.floor" placeholder="请输入楼层" />
        </el-form-item>
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="form.roomNumber" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
                v-for="dict in sys_room_status"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入住时间" prop="checkinTime">
          <el-date-picker clearable
                          v-model="form.checkinTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择入住时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="退房时间" prop="checkoutTime">
          <el-date-picker clearable
                          v-model="form.checkoutTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择退房时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="房间介绍" prop="roomDesc">
          <el-input v-model="form.roomDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="房间图片" prop="imgUrl">
          <image-upload v-model="form.imgUrl"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Room">
import { ref, reactive, toRefs, onMounted } from 'vue'
import { listRoom, getRoom, delRoom, addRoom, updateRoom } from "@/api/system/room"
import { listType } from "@/api/system/type"
import { listInfo } from "@/api/system/info"
import useUserStore from '@/store/modules/user'
import {parseTime} from "../../../utils/ruoyi.js";
const userStore = useUserStore()
const { proxy } = getCurrentInstance()
const { sys_room_status } = proxy.useDict('sys_room_status')

// 状态管理
const roomList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const hotelId = ref(null)
const hotelName = ref(null)

// 表单数据
const data = reactive({
  form: {
    freeRooms: null,
    roomId: null,
    hotelId: null,
    roomTypeId: null,
    floor: null,
    roomNumber: null,
    status: null,
    checkinTime: null,
    checkoutTime: null,
    roomDesc: null,
    imgUrl: null,
    hotelInfo: {
    }
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    hotelId: null,
    roomTypeId: null,
    floor: null,
    roomNumber: null,
    status: null,
    checkinTime: null,
    checkoutTime: null,
  },
  rules: {
    hotelId: [{ required: true, message: "酒店id不能为空", trigger: "blur" }],
    roomTypeId: [{ required: true, message: "房间类型id不能为空", trigger: "blur" }],
    floor: [{ required: true, message: "楼层不能为空", trigger: "blur" }],
    roomNumber: [{ required: true, message: "房间号不能为空", trigger: "blur" }],
  }
})

const { queryParams, form, rules } = toRefs(data)
const roomTypeList = ref([])

// 获取房间类型列表
function getRoomTypeList() {
  listType({managerId: userStore.id}).then(response => {
    roomTypeList.value = response.rows.map(item => ({
      label: item.roomTypeName,
      value: item.roomTypeId
    }))
  })
}

// 获取酒店信息并查询房间列表
function getList() {
  listInfo({managerId: userStore.id}).then(response => {
    if (!response.rows || response.rows.length === 0) {
      return listRoom({...queryParams.value, managerId: userStore.id}).then(response => {
        console.log("获取到的房间列表数据:", response.rows)
        roomList.value = response.rows || []
        total.value = response.total || 0
        loading.value = false
      })
    }
    queryParams.value.hotelId = response.rows[0].hotelId
    hotelName.value = response.rows[0].hotelName
    loading.value = true

    listRoom({...queryParams.value, managerId: userStore.id}).then(response => {
      console.log("获取到的房间列表数据:", response.rows)
      roomList.value = response.rows || []
      total.value = response.total || 0
      loading.value = false
    }).catch(err => {
      loading.value = false
      proxy.$modal.msgError(err.message || '获取房间列表失败')
    })
  }).catch(err => {
    proxy.$modal.msgError(err.message || '获取酒店信息失败')
  })
}

// 重置表单
function reset() {
  form.value = {
    roomId: null,
    hotelId: null,
    roomTypeId: null,
    floor: null,
    roomNumber: null,
    status: null,
    checkinTime: null,
    checkoutTime: null,
    roomDesc: null,
    imgUrl: null,
    freeRooms: null,
  }
  proxy.resetForm("roomRef")
}

// 取消操作
function cancel() {
  open.value = false
  reset()
}

// 搜索操作
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

// 重置搜索
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.roomId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增房间
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加房间信息"
  form.value.hotelId = hotelName.value // 设置酒店名
}

// 修改房间
function handleUpdate(row) {
  reset()
  const roomId = row?.roomId || ids.value[0]
  console.log(row)
  form.value.hotelId = row.hotelInfo.hotelName // 设置酒店名

  if (!roomId) {
    proxy.$modal.msgWarning('请选择要修改的房间')
    return
  }

  getRoom(roomId).then(response => {
    form.value = { ...response.data }
    form.value.hotelId = row.hotelInfo.hotelName
    open.value = true
    title.value = "修改房间信息"
  }).catch(err => {
    proxy.$modal.msgError(err.message || '获取房间信息失败')
  })
}

// 提交表单
function submitForm() {
  proxy.$refs["roomRef"].validate(valid => {
    if (!valid) return

    if (form.value.roomId != null) {
      // 修改
      console.log(queryParams.value.hotelId)
      updateRoom({...form.value, managerId: userStore.id, hotelId: queryParams.value.hotelId}).then(response => {
        proxy.$modal.msgSuccess("修改成功")
        open.value = false
        getList()
      }).catch(err => {
        proxy.$modal.msgError(err.message || '修改失败')
      })
    } else {
      // 新增操作：先检查房间号是否已存在
      listRoom({
        roomNumber: form.value.roomNumber,
        managerId: userStore.id,
        hotelId: queryParams.value.hotelId,
      }).then(response => {
        console.log("检查房间号是否已存在的响应:", response)
        const count = response.total || 0
        if (count > 0) {
          // 存在重复房间号
          proxy.$modal.msgError('该房间号已存在，请重新输入！')
          return
        }
        if (count === 0) {
          // 不存在重复房间号
          return addRoom({...form.value, managerId: userStore.id, hotelId: queryParams.value.hotelId}).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
        }
        // 执行新增
      })
    }
  })
}

// 删除房间
function handleDelete(row) {
  const roomIds = row?.roomId || ids.value

  if (!roomIds) {
    proxy.$modal.msgWarning('请选择要删除的房间')
    return
  }

  const roomIdStr = Array.isArray(roomIds) ? roomIds.join(',') : roomIds

  proxy.$modal.confirm(`是否确认删除房间编号为"${roomIdStr}"的数据项？`).then(() => {
    return delRoom(roomIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

// 导出数据
function handleExport() {
  proxy.download('system/room/export', {
    ...queryParams.value
  }, `room_${new Date().getTime()}.xlsx`)
}

// 生命周期钩子
onMounted(() => {
  getRoomTypeList()
  getList()
})
</script>